package com.edt.ichannel.api.service.impl;

import cc.edt.iceutils2.random.IceRandomUtils;
import cc.edt.iceutils2.string.IceStringUtils;
import cc.edt.iceutils3.json.IceFastJsonUtils;
import com.alibaba.fastjson.JSON;
import com.edt.ichannel.api.common.constant.CommonConstant;
import com.edt.ichannel.api.common.entity.ActionResult;
import com.edt.ichannel.api.entiy.local.*;
import com.edt.ichannel.api.service.*;
import com.edt.ichannel.api.service.component.RedisHandler;
import com.edt.ichannel.api.service.component.RedisLock;
import com.edt.ichannel.utils.RandomUtil;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @author update ty zyp
 */
@Service
public class TrafficServiceImpl implements TrafficService {

    @Resource
    private MechanismsAuthService mechanismsAuthService;
    @Resource
    private EdtApiService edtApiService;
    @Resource
    private FlowService flowService;
    @Resource
    private FlowExchangeLogService flowExchangeLogService;

    @Resource
    private InterfaceLogService interfaceLogService;

    @Resource
    private RedisLock redisLock;

    @Resource
    private RedisHandler redisHandler;

    @Resource
    private FlowRuleService flowRuleService;


    private Logger logger = LogManager.getLogger(TrafficServiceImpl.class);

    /**
     * 手机充值流量
     */
    @Override
    public ActionResult exchange(HttpPostParamsTraffic params) {
        ActionResult actionResult = new ActionResult();
        //验证三户
        String sanHuType = redisHandler.getSysType(params.getPhone());
        logger.info("-------------------->三户信息："+sanHuType);
        if (IceStringUtils.isBlank(sanHuType)) {
            actionResult.setSuccess(CommonConstant.ACTIONRESULT_FAIL);
            actionResult.setMessage("三户信息无效");
        }
        else {
            //充值流量
            actionResult = traffic(sanHuType, params.getPhone(), params.getFlowCode(), params.getMechanismsId(),params.getMemberType(),params.getRemark());
        }
        return actionResult;
    }

    /**
     * 手机充值流量
     */
    @Override
    @Async
    public void exchangeAsync(String phone, String flowvalue, String mechanismsid) {
        ActionResult actionResult = new ActionResult();
        //验证三户
        String sanHuType = redisHandler.getSysType(phone);
        logger.info("-------------------->三户信息："+sanHuType);
        if (IceStringUtils.isBlank(sanHuType)) {
            actionResult.setSuccess(CommonConstant.ACTIONRESULT_FAIL);
            actionResult.setMessage("三户信息无效");
        } else {
            String flowCode = flowRuleService.getFlowCodeByValue(flowvalue);
            if(IceStringUtils.isNoneBlank(flowCode)){
                actionResult = traffic(sanHuType, phone, flowCode, mechanismsid,null,null);
            }
            //充值流量
            logger.info("------------->充值结果："+ IceFastJsonUtils.toJsonString(actionResult));
        }
    }

    @Override
    public ActionResult exchange(String res) {
        ActionResult actionResult = new ActionResult();
        HttpPostParamsTraffic params;
        try {
           params = JSON.parseObject(res, HttpPostParamsTraffic.class);
        }
        catch(Exception e){
            e.getStackTrace();
            actionResult.setSuccess(false);
            actionResult.setMessage("请检查参数格式");
           return actionResult;
        }
       if(params != null){
           actionResult = validateExchangeParam(params);
           if (actionResult.isSuccess()) {
               actionResult = exchange(params);
           }
       }
        interfaceLogService.addLog(actionResult,res,"/traffic/exchange",CommonConstant.INTERFACE_TYPE_COLLECT_EXCHANGE);
        return actionResult;
    }


    /**
     * 通过条件查询流量充值信息
     * @param mechanismsId 渠道ID
     * @param phone 充值电话号
     * @return 返回值
     */
    @Override
    public ActionResult getTraffiicByMechanismsIdAndPhone(String mechanismsId, String phone) {
        ActionResult actionResult = new ActionResult();
        if(IceStringUtils.isAnyBlank(mechanismsId,phone)){
            actionResult.setSuccess(CommonConstant.ACTIONRESULT_FAIL);
            actionResult.setMessage("查询信息不完整");
        }else{
            List<FlowExchangeLogDetail> list = flowExchangeLogService.getFlowExchangeLogByCondition(mechanismsId,phone);
            actionResult.setSuccess(CommonConstant.ACTIONRESULT_TRUE);
            actionResult.setResultList(list);
        }
        return actionResult;
    }

    /**
     * 充值流量
     * @param sanHuType 三户类型
     * @param phone 充值手机号
     * @param mechanismsId 渠道ID(记录充值日志)
     * @param memberType 会员身份
     * @param remark 备注
     * @return 返回值
     */
    private ActionResult traffic(String sanHuType, String phone, String flowCode, String mechanismsId, String memberType, String remark) {
        ActionResult actionResult = new ActionResult();
        String lockKey = CommonConstant.LOCK_KEY_TRAFFIC+phone;
        String lockValue = IceRandomUtils.longUUID();
        try{

           if( redisLock.tryLock(lockKey,lockValue,CommonConstant.LOCK_TRAFFIC_TIMEOUT)){
               //获取可充值的流量包
               String dateFormat = new SimpleDateFormat("yyyy-MM").format(new Date());
               List<Flow> flows = flowService.getFlowByPhone(flowCode,phone,dateFormat,sanHuType);

               if(flows == null ){
                   actionResult.setSuccess(CommonConstant.ACTIONRESULT_FAIL);
                   actionResult.setMessage("无可充值流量包");
                   return actionResult;
               }
               if(flows.isEmpty()){
                   actionResult.setSuccess(CommonConstant.ACTIONRESULT_FAIL);
                   actionResult.setMessage("无可充值流量包");
                   return actionResult;
               }
               Flow flow = flows.get(RandomUtil.getInt(flows.size()));
               EdtApiParamEntity edtApiParamEntity = new EdtApiParamEntity();
               edtApiParamEntity.setPhone(phone);

               edtApiParamEntity.setProductId(flow.getProductId());
               edtApiParamEntity.setPackageId(flow.getPackageId());
               edtApiParamEntity.setElementId(flow.getElementId());
               edtApiParamEntity.setEnableTag("1");
               edtApiParamEntity.setServiceId(flow.getServiceId());
               edtApiParamEntity.setOptType("00");

               if(IceStringUtils.equals("1",sanHuType)){
                   //ESS充值流量
                   actionResult = edtApiService.trafficEss(edtApiParamEntity);
               }else if( IceStringUtils.equals("2",sanHuType)){
                   //CBSS充值流量
                   actionResult = edtApiService.trafficCbss(edtApiParamEntity);
               }
               else {
                   actionResult.setSuccess(CommonConstant.ACTIONRESULT_FAIL);
                   actionResult.setMessage("三户用户类型无效");
                   return actionResult;
               }
               //记录日志
               this.saveFlowExchangeLog(phone,mechanismsId,memberType,remark,flow,actionResult);
           }else{
               actionResult.setSuccess(false);
               actionResult.setMessage("lock timeout:请联系接口负责人排查错误");
           }

        }catch (Exception ex){
            actionResult.setSuccess(false);
            actionResult.setMessage("充值流量出现错误");
        }finally {
            logger.info("-----------释放锁-------------------------");
            redisLock.releaseLock(lockKey,lockValue);
        }
        return actionResult;
    }

    private void saveFlowExchangeLog(String phone, String mechanismsId, String memberType, String remark, Flow flow, ActionResult actionResult) {
        FlowExchangeLog flowExchangeLog = new FlowExchangeLog();
        flowExchangeLog.setMechanismsId(mechanismsId);
        flowExchangeLog.setExchangePhone(phone);
        flowExchangeLog.setFlowRuleId(flow.getFlowRuleId());
        flowExchangeLog.setPackageId(flow.getPackageId());
        flowExchangeLog.setPackageName(flow.getPackageName());
        flowExchangeLog.setProductId(flow.getProductId());
        flowExchangeLog.setProductName(flow.getProductName());
        flowExchangeLog.setElementId(flow.getElementId());
        flowExchangeLog.setServiceId(flow.getServiceId());
        flowExchangeLog.setElementName(flow.getElementName());
        flowExchangeLog.setExchangeResult(actionResult.isSuccess()?1:0);
        flowExchangeLog.setExchangeDate(new Date());
        flowExchangeLog.setFlag(flow.getFlag());
        flowExchangeLog.setMemberType(memberType);
        flowExchangeLog.setRemark(remark);
        flowExchangeLogService.saveFlowExchangeLog(flowExchangeLog);
    }


    private ActionResult validateExchangeParam(HttpPostParamsTraffic params) {
        ActionResult result = new ActionResult();
        if(params == null){
            result.setSuccess(false);
            result.setMessage("接收参数为空");
            return result;
        }
        if(params.getMechanismsId() == null || "".equals(params.getMechanismsId())){
            result.setSuccess(false);
            result.setMessage("mechanismsid 节点为空，请核对");
            return result;
        }
        if(params.getUser() == null || "".equals(params.getUser())){
            result.setSuccess(false);
            result.setMessage("user 节点为空，请核对");
            return result;
        }
        if(params.getPwd() == null || "".equals(params.getPwd())){
            result.setSuccess(false);
            result.setMessage("pwd 节点为空，请核对");
            return result;
        }
        if(params.getPhone() == null || "".equals(params.getPhone())){
            result.setSuccess(false);
            result.setMessage("phone 节点为空，请核对");
            return result;
        }
        if(params.getFlowCode() == null || "".equals(params.getFlowCode())){
            result.setSuccess(false);
            result.setMessage("flowcode 节点为空，请核对");
            return result;
        }
        if(IceStringUtils.isBlank(params.getMemberType())){
            result.setSuccess(false);
            result.setMessage("memberType 节点为空，请核对");
            return result;
        }

        int count = mechanismsAuthService.getCountByCondition(params.getMechanismsId(),params.getUser(), params.getPwd());
        if (count==0)
        {
            result.setSuccess(false);
            result.setMessage("渠道无效");
            return result;
        }
        result.setSuccess(true);
        result.setMessage("验证通过");
        return result;
    }


}
